using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using xjjxmm.infrastructure.Authorizations;
using XjjXmm.Infrastructure.Configuration;
using XjjXmm.Infrastructure.Constant;
using XjjXmm.Infrastructure.Exceptions;
using xjjxmm.infrastructure.ToolKit;
using XjjXmm.Infrastructure.User;
using System.Reflection;
using System;
using XjjXmm.Infrastructure.Common;
using XjjXmm.Infrastructure.ToolKit;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using xjjxmm.infrastructure.Webs;
using xjjxmm.infrastructure.xjjxmmLog.LogKit;

namespace xjjxmm.infrastructure.Middleware;


public class ExceptionHandlerMiddleware : IMiddleware
{
    private readonly ILog<ExceptionHandlerMiddleware> _log;
    private readonly ThreadLocalContext _threadLocalContext;
   

    public  ExceptionHandlerMiddleware(ILog<ExceptionHandlerMiddleware> log,
        ThreadLocalContext threadLocalContext)
    {
        _log = log;
        _threadLocalContext = threadLocalContext;
     
    }

    public async Task InvokeAsync(HttpContext httpContext, RequestDelegate next)
    {
        try
        {
           // userThreadContext.Set(null);
            //_log.Debug("before exception");
            await next(httpContext);
        }
        catch (Exception e)
        {
            var error = new Response<string>()
            {
                Success = false,
                Code = "-1",
                Message = e.Message
            };

            httpContext.Response.ContentType = "text/json;charset=utf-8;";
            var output = JsonConvert.SerializeObject(error, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            await httpContext.Response.WriteAsync(output);
        }
        finally
        {
            _threadLocalContext.Clear();
           // _log.Debug("end exception");
        }
    }
}